package com.nextive.interview.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.nextive.interview.R;
import com.nextive.interview.dto.UserPreferences;
import com.nextive.interview.service.UserInfoService;
import com.nextive.interview.service.UserInfoService.METRICS;
import com.nextive.interview.service.impl.UserInfoServiceImpl;
import com.nextive.interview.util.PhoneContactsUtil;

public class SettingsActivity extends Activity {
    
	private UserInfoService userInfoService;
	
	// TODO - should we have these member fields ???
	private EditText nameInput;
	private EditText emailInput;
	//private EditText optionsInput;
	private Button confirmButton;
	private Button recipientButton;
	private TextView recipientDisplay;
	private RadioButton kgRadioButton;
	private RadioButton lbRadioButton;
	private boolean userFirstTime = false;
//	private EditText recipientInput;
	
	private static final String MYSELF_CONTACT = "Myself";
	private static final String CHOOSE_CONTACT = "Choose contact";
	private static final String CREATE_NEW_CONTACT = "Create new contact";
	
	private static final int ACTIVITY_CHOOSE = 0;
	private static final int ACTIVITY_CREATE = 1;
	
	private static final int RECIPIENT_DIALOG_ID = 0;
	
	/**
	 * This enum is used to know if we want to change settings or not.
	 */
	public enum SETTINGS_MODE {
		
		CHANGE_SETTINGS;
		
	}
	
	public SettingsActivity() {
		
		this.userInfoService = new UserInfoServiceImpl(this);
		
	}
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	super.onCreate(savedInstanceState);
    	userFirstTime = userInfoService.isUserFirstAccess(); 
    	if (userFirstTime || isChangeSettingsAction()) {
        	
    		setContentView(R.layout.initial_set_up);
    		bindInputs();
    		configureSettingsLayout(savedInstanceState);
        	
        } else {
        	
        	forwardToListActivity();
        	
        }
    	
    }
    
    private boolean isChangeSettingsAction() {
    	
    	return getIntent().hasExtra(SETTINGS_MODE.CHANGE_SETTINGS.name());
    	
    }
    
    private void bindInputs() {

        nameInput = (EditText) findViewById(R.id.name);
        emailInput = (EditText) findViewById(R.id.email);
        kgRadioButton = (RadioButton) findViewById(R.id.kg_option);
        lbRadioButton = (RadioButton) findViewById(R.id.lb_option);
        confirmButton = (Button) findViewById(R.id.confirm_setup);
        recipientButton = (Button) findViewById(R.id.pickUpRecipient);
        recipientDisplay = (TextView) findViewById(R.id.recipient_display);

    }
    
    private void configureSettingsLayout(Bundle savedInstanceState) {

        configureRecipientButton();
        configureConfirmButton();
        
        if (!userFirstTime) {
        	
        	populateSettingsInfo();
        	
        } else {
        	
        	updateMetricsDisplay(METRICS.KG);
        	
        }
        	

    }
    
    private void populateSettingsInfo() {
    	
    	UserPreferences userPreferences = userInfoService.fetchUserInfo();
    	
    	nameInput.setText(userPreferences.getName());
    	emailInput.setText(userPreferences.getEmail());
    	updateRecipientDisplay(userPreferences.getRecipientEmail());
    	updateMetricsDisplay(userPreferences.getMetricOption());
    	
    }
    
    private void updateMetricsDisplay(METRICS metric) {
    
    	kgRadioButton.setChecked(METRICS.KG.equals(metric));
    	lbRadioButton.setChecked(METRICS.LB.equals(metric));
    	
    }
    
    private void updateRecipientDisplay(String email) {
    
    	recipientDisplay.setText(email);
    	
    }
    
	private void configureRecipientButton() {

		recipientButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			
				showDialog(RECIPIENT_DIALOG_ID);
				
			}
		});

	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		
		switch (id) {
		case RECIPIENT_DIALOG_ID:
			String[] items = {MYSELF_CONTACT, CHOOSE_CONTACT, CREATE_NEW_CONTACT};
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.select_contact_option);
			builder.setItems(items, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
				
					switch (which) {
					case 0:
						// Myself contact
						// TODO - would be better to disable "myself" button if email has nto been set yet !
						manageMyselfContact();
						break;
					case 1:
						// Choose an existing contact
						forwardToChooseContactActivity();
						break;
					case 2:
						// Create a new contact
						forwardToCreateNewContactActivity();
						break;
					}
					
				}
			});
			
			return builder.show();
			
//			return new DatePickerDialog(this, new OnDateSetListener() {
//				
//				@Override
//				public void onDateSet(DatePicker view, int yearIn, int monthOfYear,
//						int dayOfMonth) {
//
//					year = yearIn;
//					month = monthOfYear;
//					day = dayOfMonth;
//					updateDateDisplay();
//					
//				}
//			}, year, month, day);
		}
		
		return null;
	}

	private void manageMyselfContact() {
	
		String email = emailInput.getText().toString();
		if (email != null && !"".equals(email))
			updateRecipientDisplay(email);
		
		setResult(RESULT_OK);
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		super.onActivityResult(requestCode, resultCode, data);
		
		String recipientEmail = data.getStringExtra(UserInfoService.USER_INFO_KEYS.EMAIL.name()).toString();
		updateRecipientDisplay(recipientEmail);
		
	}

	// TODO - I do NOT KNOW what to do here !!! new activity ?
	private void forwardToCreateNewContactActivity() {
		
		Intent intent = new Intent(this, CreateNewContactActivity.class);
		startActivityForResult(intent, ACTIVITY_CREATE);
		
	}

	private void forwardToChooseContactActivity() {
		
		Intent intent = new Intent(this, ChooseContactActivity.class);
		startActivityForResult(intent, ACTIVITY_CHOOSE);
		
	}

	/**
     * It forwards current flow to list activity.
     */
    private void forwardToListActivity() {
    	
    	Intent intent = new Intent(this, ViewWeightListActivity.class);
//    	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	
    	startActivity(intent);
    	
    }

    /**
     * It is in charge of initializing recipient button. This means, add corresponding listener.
     */
//    private void configureRecipientButton() {
//    	
//    	recipientButton.setOnClickListener(new OnClickListener() {
//			
//			// TODO - check fi we are going to have this button or not !
//    		@Override
//			public void onClick(View v) {
//			
//				
//			}
//		});
//    }
    
    private void configureConfirmButton() {
    	
    	confirmButton.setOnClickListener(new OnClickListener() {
			
    		@Override
			public void onClick(View v) {
			
				String name = nameInput.getText().toString();
				String email = emailInput.getText().toString();
				String recipient = recipientDisplay.getText().toString();
				METRICS metricOption = kgRadioButton.isChecked() ? METRICS.KG : METRICS.LB;
				
    			// TODO - any validation on the email ???
				
				userInfoService.saveUserInfo(name, email, recipient, metricOption);
				
				forwardToListActivity();
				
			}
		});
    	
    }
}